package com.bjpowernode.web.interceptor;

import org.apache.commons.lang3.StringUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.concurrent.TimeUnit;

@Component // Spring自动扫描，并交给容器管理
public class CommonsInterceptor implements HandlerInterceptor {

    // 方法上的注解要想被Spring解析，则类上必须有Spring的注解
    @Resource
    private RedisTemplate redisTemplate;

    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response,
                             Object handler) throws Exception {
        // 重置登录活跃的30分钟
        String token = request.getHeader("token");
        if (StringUtils.isNotBlank(token) && redisTemplate.opsForValue().get(token) != null) {
            redisTemplate.expire(token, 30, TimeUnit.MINUTES);
        }

        // 放行
        return true;
    }
}
